//
//  ViewController.swift
//  webViewProgress
//
//  Created by 李煜 on 2024/1/25.
//

import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate {
    // wkWebView

    lazy var webView: WKWebView = {
        // 创建WKPreferences

        let preferences = WKPreferences()

        // 开启js

        // 创建WKWebViewConfiguration

        let configuration = WKWebViewConfiguration()

        if #available(iOS 13, *) {
            preferences.javaScriptEnabled = true
        }
        if #available(iOS 14, *) {
            let pagePreference = WKWebpagePreferences()
            pagePreference.allowsContentJavaScript = true
        }

        // 设置WKWebViewConfiguration的WKPreferences

        configuration.preferences = preferences

        // 创建WKUserContentController

        let userContentController = WKUserContentController()

        // 配置WKWebViewConfiguration的WKUserContentController

        configuration.userContentController = userContentController

        // 给WKWebView与Swift交互起一个名字：callbackHandler，WKWebView给Swift发消息的时候会用到

        // 此句要求实现WKScriptMessageHandler协议

        configuration.userContentController.add(self, name: "callbackHandler")

        // 创建WKWebView

        var webView = WKWebView(frame: CGRect.zero, configuration: configuration)

        // 让webview翻动有回弹效果

        webView.scrollView.bounces = true

        // 只允许webview上下滚动

        webView.scrollView.alwaysBounceVertical = true

        // 此句要求实现WKNavigationDelegate协议

        webView.navigationDelegate = self; webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none';document.documentElement.style.webkitUserSelect='none';", completionHandler: nil)

        return webView

    }()

    // 进度条

    lazy var progressView: UIProgressView = {
        var progressView = UIProgressView()

        progressView.progressTintColor = UIColor.red

        progressView.trackTintColor = UIColor.clear

        return progressView

    }()

    override func viewWillDisappear(_ animated: Bool) {
        self.webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        self.view.backgroundColor = UIColor.white

        self.initInterface()
    }

    func initInterface() {
        self.view.addSubview(self.webView)

        self.webView.frame = view.bounds

        // 创建网址

        let url = NSURL(string: "http://www.baidu.com")

        // 创建请求

        let request = NSURLRequest(url: url! as URL)

        // 加载请求

        self.webView.load(request as URLRequest)

        self.view.addSubview(self.progressView)

        self.progressView.frame = CGRectMake(0, 0, view.bounds.width, 5)
        // 进度条的进度监听
        self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.alpha = 1.0

            self.progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)

            // 进度条的值最大为1.0

            if self.webView.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () in

                    self.progressView.alpha = 0.0

                }, completion: { (_: Bool) in

                    self.progressView.progress = 0

                })
            }
        }
    }

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {}

    // 加载完毕以后执行，自适应屏幕宽度，有的屏幕不自适应，需要自适应屏幕宽度

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("""

        var oMeta = document.createElement('meta');

        oMeta.content = 'width=device-width, initial-scale=1, user-scalable=0';

        oMeta.name = 'viewport';

        document.getElementsByTagName('head')[0].appendChild(oMeta);

        """, completionHandler: nil)
    }

    // 处理网页加载失败

    private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        self.progressView.progress = 0
    }

    // 处理网页加载完成

    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {}

    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.progressView.progress = 0
    }
}
